package jml.defaultimple.web;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jml.config.Config;
import jml.config.cmd.Command;
import jml.config.cmd.CommandExec;
import jml.config.cmd.CommandGroup;
import jml.defaultimple.util.TittleComparatorImple;
import jml.defaultimple.util.UFile;

@WebServlet("/slideshow")
public class ServletSlider extends HttpServlet
{
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException
	{
		// recibo el path del title a tocar
		String titlePath = request.getParameter("path");
		String titlePathOK = URLDecoder.decode(titlePath, "UTF-8");
	
		// obtengo los external commands
		CommandGroup ec = Config.getConfig(true).getCommandGroup();
		
		// obtengo el slideshow

		
//		// argumentos
//		ArrayList<String> args = new ArrayList<String>();
//		args.add(ec.getRuntimeScript());
//		args.add(ec.getDefaultScript());
//		args.add(ss.getPath());
		
//		String imageFolder =UFile.getShortFilename(titlePathOK+"\\"+ss.getFolder()); 
		
		try
		{
//			Integer x = (Integer)request.getAttribute("delay");
			String x = request.getParameter("delay");
			if( x!=null )
			{
				Thread.sleep(Integer.parseInt(x));
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}

		// obtengo el comando
		Command ss = ec.getComnand("SLIDESHOW","default");
		
		// verifique si existe el path
		
		String fullpath = titlePathOK+"\\"+ss.getProps().get("folder");
		File f = new File(fullpath);
		if( f.exists() )
		{
			String ff = UFile.getShortFilename(fullpath);
			ff+="/"+ss.getProps().get("files");
			ss.getAppParams().put("FULLPATH",ff);	
			CommandExec.exec(ss);
		}
		else
		{
			String onNoScans = ss.getProps().get("if-no-scans");
			if( onNoScans.equals("open-folder") )
			{
				request.getRequestDispatcher("/explore").forward(request,response);
			}
			else
			{
				if( onNoScans.equals("show-default") )
				{
					String xxx = getServletContext().getRealPath(ss.getProps().get("default-image"));
					ss.getAppParams().put("FULLPATH",xxx);
					CommandExec.exec(ss);
				}
			}
		}
	
		return;
	}
}
